#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int pipefd[2] = {0};

    int ret = pipe(pipefd);
    if (ret < 0) {
        perror("pipe error");
        return -1;
    }

    pid_t id = fork();
    if (id < 0) {
        perror("fork error");
        return -1;
    }else if (id == 0) {
        //child
        int total = 0, i = 0;
        char *data = "今天的天气还不错！";
        //ssize_t write(int fd,  void *data,  int len);
        while(1) {
            char buf[1024] = {0};
            sprintf(buf, "%s--%d\n", data, i++);
            int ret = write(pipefd[1], buf, strlen(buf));
            total += ret;
            printf("total:%d\n", total);
            sleep(1);
        }
    }else {
        //parent
        while(1){
            char buf[1024] = {0};
            int ret = read(pipefd[0], buf, 1023);
            if (ret == 0) {
                printf("all write closed!\n");
            }
            printf("rbuf:%s", buf);
            sleep(2);
        }
    }
    return 0;
}
